#include "texturemanager.h"
#include <QInputDialog>
#include <QFile>
#include <QDir>
#include <QMessageBox>
#include <QDebug>
#include <Shinygami/datafile.hpp>
#include "yamlstream.h"
#include <QFile>
#include <QTextStream>


#ifdef WIN32
# define PATH_SLASH '\\'
#else
# define PATH_SLASH '/'
#endif

QString GetNameFromPath(const QString& filepath);
QString GetFilepathFromPath(const QString&);

TextureManager::TextureManager(QObject *parent) : QObject(parent)
{
}

bool TextureManager::AddFile(QString filepath)
{
  QDir           __directory(_directory);
  QString        directory = __directory.absolutePath();
  QString        imagePath;
  TexturePair    pair;

  do
  {
      pair.first = QInputDialog::getText(0, "Texture name", "Name", QLineEdit::Normal, GetNameFromPath(filepath));
      pair.first.replace('#', '-');
      if (GetByName(pair.first))
	  QMessageBox::warning(0, "Erreur", "Ce nom est deja utilise");
  } while (GetByName(pair.first));
  if (pair.first == "")
      return (false);
  if (filepath.startsWith(directory))
    pair.source = filepath.mid(directory.length() + 1);
  else
  {
      QString destination = GetFilepathFromPath(filepath);

      if (!(QFile::copy(filepath, _directory + "/" + destination)))
      {
	  QMessageBox::warning(0, "Erreur", "Impossible de copier l'image. Un fichier du meme nom existe peut-etre deja.");
	  return (false);
      }
      pair.source = destination;
  }
  imagePath = _directory + "/" + pair.source;
  if (pair.second.LoadFromFile(imagePath.toStdString()))
  {
      Shiny::TextureList::Add(pair.first.toStdString(), &pair.second);
      _textures << pair;
      TextureAdded(pair.first);
      return (true);
  }
  return (false);
}

void TextureManager::DeleteTexture(QString name)
{
    int res = QMessageBox::warning(0, "Suppression de texture", "Etes-vous sur de vouloir supprimer " + name + " ?", QMessageBox::Yes, QMessageBox::No);

    if (res == QMessageBox::Yes)
    {
	QList<TexturePair>::iterator current = _textures.begin();
	QList<TexturePair>::iterator end     = _textures.end();

	while (current != end)
	{
	    if ((*current).first == name)
	    {
		_textures.erase(current);
		TextureDeleted(name);
		break ;
	    }
	    ++current;
	}
    }
}

const sf::Texture* TextureManager::GetByName(const QString &name) const
{
    QList<TexturePair>::const_iterator current = _textures.begin();
    QList<TexturePair>::const_iterator end     = _textures.end();

    while (current != end)
    {
        if ((*current).first == name)
            return (&((*current).second));
        ++current;
    }
    return (0);
}

sf::Texture* TextureManager::GetByName(const QString &name)
{
    QList<TexturePair>::iterator current = _textures.begin();
    QList<TexturePair>::iterator end     = _textures.end();

    while (current != end)
    {
        if ((*current).first == name)
            return (&((*current).second));
        ++current;
    }
    return (0);
}

void TextureManager::Load(const QString &filepath)
{
    DataTree* file = DataTree::Factory::Yaml(filepath.toStdString());
    Data      data(file);

    if (file)
    {
        Data::iterator current = data.begin();
        Data::iterator end     = data.end();

        for (; current != end ; ++current)
        {
            TexturePair pair;
            QString     texturePath;

            pair.first  = (*current).Key().c_str();
            pair.source = (*current).Value().c_str();
            texturePath = _directory + PATH_SLASH + pair.source;
	    qDebug() << texturePath;
            if (pair.second.LoadFromFile(texturePath.toStdString()))
            {
		Shiny::TextureList::Add(pair.first.toStdString(), &pair.second);
                _textures << pair;
                TextureAdded(pair.first);
            }
        }
        delete file;
    }
    else
	qDebug() << "Can't load texture file " << filepath;
}

void TextureManager::Save(const QString &filepath)
{
    QList<TexturePair>::iterator current = _textures.begin();
    QList<TexturePair>::iterator end     = _textures.end();
    YamlStream                   stream;
    QFile                        file(filepath);

    for (; current != end ; ++current)
    {
        QPair<QString, std::string> pair;

        pair.first  = (*current).first;
        pair.second = (*current).source.toStdString();
        stream << pair;
    }
    if (file.open(QFile::WriteOnly))
    {
        QTextStream out(&file);

        out << stream.str().c_str();
        file.close();
    }
}
